package com.sdry.web.controller.approval;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sdry.constant.PartsResult;
import com.sdry.constant.PartsResultConstant;
import com.sdry.entity.AnnotationInfo;
import com.sdry.entity.ApprovalCustomEntity;
import com.sdry.entity.ApprovalEntity;
import com.sdry.entity.PageEntity;
import com.sdry.entity.Project;
import com.sdry.entity.ProjectApproval;
import com.sdry.entity.ProjectApprovalExample;
import com.sdry.entity.ProjectExample;
import com.sdry.entity.agreement.Agreement;
import com.sdry.entity.approvalManagement.ApprovalDetail;
import com.sdry.entity.approvalManagement.ModelEntity;
import com.sdry.entity.base.Department;
import com.sdry.entity.base.Staff;
import com.sdry.service.ApprovalInitiateService;
import com.sdry.service.ProjectApprovalService;
import com.sdry.service.ProjectService;
import com.sdry.service.approval.ApprovalService;
import com.sdry.service.base.StaffService;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.RootPath;
import com.sdry.utils.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * 
 * @ClassName ApprovalController
 * @Description 提交审批
 * @Author lz
 * @Date 2018年8月30日 10:29:19
 * @Version 1.0
 */
@Controller
@RequestMapping("/approval")
public class ApprovalController {

	@Resource
	ApprovalService approvalService;
	
	@Resource
	ApprovalInitiateService approvalInitiateService;
	
	@Resource
	StaffService staffService;
	
	@Resource
	ProjectService projectService;
	
	@Resource
	ProjectApprovalService projectApprovalService;
	
	/**
	 * 进入提交审批页面
	 * @return
	 */
	@RequestMapping("/selectDept")
	public String selectDept(){
		return "/approval/selectDept";
	}
	
	/**
	 * 进入我发起的页面
	 * @return
	 */
	@RequestMapping("/toApprovalPage")
	public ModelAndView toApprovalPage(){
		ModelAndView mv = new ModelAndView();
		List<ModelEntity> modelEntityList = approvalInitiateService.listAllModel();
		mv.addObject("modelList", modelEntityList);
		mv.setViewName("/approval/approval");
		return mv;
	}
	
	/**
	 * 项目打包
	 * @return
	 */
	@RequestMapping("/toApprovalPackage/{ids}")
	@ResponseBody
	public Object toApprovalPackage(Project project, @PathVariable("ids") String ids, HttpSession session){
		// 校验代码
		ProjectExample example = new ProjectExample();
		example.createCriteria().andNameEqualTo(project.getName());
		List<Project> projectExit = projectService.selectByExample(example);
		if(projectExit.size() > 0) {
			return new PartsResult(PartsResultConstant.FAILED, "项目名称重复");
		}
		String[] idArrayExit = ids.split("-");
		if(idArrayExit.length > 0) {
			for (String idStr : idArrayExit) {
				if (StringUtils.isBlank(idStr)) {
					continue;
				}
				ProjectApprovalExample examplep = new ProjectApprovalExample();
				examplep.createCriteria().andApprovalIdEqualTo(Long.parseLong(idStr));
				List<ProjectApproval> lists= projectApprovalService.selectByExample(examplep);
				if(lists.size() > 0) {
					return new PartsResult(PartsResultConstant.FAILED, "审批条目不能重复打包");
				}
			}
		}
		
		Staff staffSession = (Staff) session.getAttribute("staff");
		int count = 0;
		String[] idArray = ids.split("-");
		if(idArray.length >= 0) {
			project.setStaffId(staffSession.getStaid());
			int coun = projectService.insert(project);
			for (String idStr : idArray) {
				if (StringUtils.isBlank(idStr)) {
					continue;
				}
				ProjectApproval projectApproval = new ProjectApproval();
				projectApproval.setProjectId(project.getId());
				projectApproval.setApprovalId(Long.parseLong(idStr));
				int change = projectApprovalService.insert(projectApproval);
				count = change + count;
			}
		}
		if (count == 0) {
			return new PartsResult(PartsResultConstant.FAILED, "");
		}
		return new PartsResult(PartsResultConstant.SUCCESS, 1);
	}
	
	/**
	 * 分页查询所有待审批
	 * @param apprpvalEntity 审批实体
	 * @param pageEntity 分页参数
	 * @param request 请求
	 * @param response 响应
	 * @return
	 * @throws Exception 异常
	 */
	@RequestMapping("/approvals")
	public void approval(ApprovalEntity apprpvalEntity, PageEntity pageEntity, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{
		pageEntity.setPage(Integer.parseInt(request.getParameter("offset")));
		pageEntity.setPageSize(Integer.parseInt(request.getParameter("limit")));
		if (StringUtil.isNotEmpty(pageEntity.getStartDate()) && StringUtil.isNotEmpty(pageEntity.getOverDate())) {
			pageEntity.setStartDate(pageEntity.getStartDate());
			pageEntity.setOverDate(pageEntity.getOverDate());
		}else{
			pageEntity.setStartDate(null);
			pageEntity.setOverDate(null);
		}
		if (StringUtil.isNotEmpty(pageEntity.getKey01())) {
			pageEntity.setKey01(pageEntity.getKey01());
		}else{
			pageEntity.setKey01(null);
		}
		Staff staffSession = (Staff) session.getAttribute("staff");
		if ("admin".equals(staffSession.getScode())) {
			pageEntity.setKey02("");
		}else{
			pageEntity.setKey02(staffSession.getSname());
		}
		
		List<ApprovalCustomEntity> receicePayList = approvalService.queryAllApproval(pageEntity);
		Long receicePayCount = approvalService.queryAllApprovalCount(pageEntity);
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:dd"));
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(receicePayList , config);
		jsonObject.put("rows", jsonArray);
		jsonObject.put("total", receicePayCount);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 合同协议和各种审批提交
	 * @param approvalDetail 审批详细信息
	 * @param modelValue 自定义表单字段
	 * @param aname 合同协议类型
	 * @param status03 审批类型
	 * @param appendDept 部门审批顺序
	 * @param response 响应
	 * @param session Session域
	 * @throws Exception 异常
	 */
	@RequestMapping("/insertDept")
	public void insertDept(ApprovalDetail approvalDetail, String[] modelValue, String aname, 
			String status03, String types, String appendDept, @RequestParam("attachment") MultipartFile attachment,
			HttpServletResponse response, HttpSession session) throws Exception{
		Integer affectRow;
		ApprovalEntity approval = new ApprovalEntity();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String deptStr = appendDept.replace("—>", ",");
		// 审批状态
		approval.setStatus01(String.valueOf(0));
		// 部门审批顺序
		approval.setStatus02(deptStr);
		//审批人类型
		approval.setTypes(types);
		// 申请类型
		if (StringUtil.isNotEmpty(aname)) {
			approval.setStatus03("合同协议");
		} else {
			approval.setStatus03(status03);
		}
		/*_________________________________________*/
		// String uploadURL = "E:/develop/EclipseLuna/git/approval/src/main/webapp/attachment/";
		if (null != attachment.getOriginalFilename() && !"".equals(attachment.getOriginalFilename())) {
			String fileName = attachment.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			String name = fileName.substring(0,fileName.lastIndexOf("."));
			String uploadURL = RootPath.getRootPath("NATIVE_PATH");
			String oriFileName = name + "_" + sdf2.format(new Date()) + suffix;
	        String path = uploadURL + oriFileName;
	        File newFile = new File(path);
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        attachment.transferTo(newFile);
			/*_________________________________________*/
			if (attachment.equals(null)) {
				approval.setRemark06(null);
			} else {
				approval.setRemark06(oriFileName);
			}
		}
		approval.setApprovalTime(sdf.format(date.getTime()));
		Staff staffSession = (Staff) session.getAttribute("staff");
		approval.setApplicant(staffSession.getSname());
		affectRow = approvalService.insertDept(approval);
		approvalDetail.setApprovalId(affectRow);
		if (null != modelValue) {
			affectRow = approvalInitiateService.saveApprovalDetail(approvalDetail, modelValue);
		}
		if (affectRow > 0) {
			ResponseUtil.write(response, affectRow);
		} else {
			ResponseUtil.write(response, 0);
		}
	}
	
	/**
	 * 查询所有部门
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllDept")
	public void queryAllDept(HttpServletResponse response) throws Exception{
		List<Department> deptList = approvalService.queryAllDept();
		if (deptList.size() > 0) {
            JSONArray jsonArray = JSONArray.fromObject(deptList);
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
	}
	
	
	/**
	 * 查询所有部门
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryPeopleByDept")
	public void queryPeopleByDept(HttpServletResponse response,Long did) throws Exception{
		List<Staff> list = approvalService.queryPeopleByDept(did);
		if (list.size() > 0) {
			JSONArray jsonArray = JSONArray.fromObject(list);
			ResponseUtil.write(response, jsonArray);
		} 
	}
	
	/**
	 * 审批
	 * @param response
	 * @param msg 审批意见
	 * @param approvalid 审批ID
	 * @param type 审批类型（1同意    2驳回）
	 * @param session
	 * @throws Exception
	 */
	@RequestMapping(value="/approvalOperate")
	public void approvalOperate(HttpServletResponse response,String msg,long approvalid,String type,HttpSession session) throws Exception{
		int isSuccess = 0;
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Staff staffSession = (Staff) session.getAttribute("staff");
		ApprovalEntity approval = approvalService.findApprovalEntityByID(approvalid);
		String[] deptList = approval.getStatus02().split(",");
		String dname = staffSession.getDepartment().getDname();
		String sname = staffSession.getSname();
		int num = 0;
		
		String types = approval.getTypes();
		
		if("1".equals(types)) {
			
			String department = "财务部";
			if(department.equals(dname)) {
				sname = sname+"[财务部]";
			}
			
			for (int i = 0; i < deptList.length; i++) {
				if (sname.equals(deptList[i])) {
					num = i;
				}
			}
		}else {
			for (int i = 0; i < deptList.length; i++) {
				if (dname.equals(deptList[i])) {
					num = i;
				}
			}
		}
		
		if (StringUtil.isNotEmpty(approval.getRemark05())) {
			approval.setRemark05(approval.getRemark05()+staffSession.getStaid()+",");
		} else {
			approval.setRemark05(staffSession.getStaid()+",");
		}
		if (num == deptList.length-1) {
			approval.setFinishTime(sdf.format(new Date().getTime()));
		}
		if (num == 0) {
			approval.setApprover01(msg);
			approval.setRemark01(sdf.format(new Date().getTime()));
			if (null == type) {
				approval.setStatus01("a1");
			} else {
				if (type.equals("1")) {
					approval.setStatus01("a1");
				} else {
					approval.setStatus01("a2");
					approval.setFinishTime(sdf.format(new Date().getTime()));
				}
			}
		}
		if (num == 1) {
			approval.setApprover02(msg);
			approval.setRemark02(sdf.format(new Date().getTime()));
			if (null == type) {
				approval.setStatus01("b1");
			} else {
				if (type.equals("1")) {
					approval.setStatus01("b1");
				} else {
					approval.setStatus01("b2");
					approval.setFinishTime(sdf.format(new Date().getTime()));
				}
			}
		}
		if (num == 2) {
			approval.setApprover03(msg);
			approval.setRemark03(sdf.format(new Date().getTime()));
			if (null == type) {
				approval.setStatus01("c1");
			} else {
				if (type.equals("1")) {
					approval.setStatus01("c1");
				} else {
					approval.setStatus01("c2");
					approval.setFinishTime(sdf.format(new Date().getTime()));
				}
			}
		}
		if (num == 3) {
			approval.setApprover04(msg);
			approval.setRemark04(sdf.format(new Date().getTime()));
			if (null == type) {
				approval.setStatus01("d1");
			} else {
				if (type.equals("1")) {
					approval.setStatus01("d1");
				} else {
					approval.setStatus01("d2");
					approval.setFinishTime(sdf.format(new Date().getTime()));
				}
			}
		}
		isSuccess = approvalService.setStatus(approval);
		if (isSuccess > 0) {
            ResponseUtil.write(response, 1);
        } else {
            ResponseUtil.write(response, 0);
        }
	}
	
	@RequestMapping("/queryHTMLByAppId")
	public void queryHTMLByAppId(String approvalId, HttpServletResponse response) throws Exception{
			
		Agreement agreement = new Agreement();
		List<Agreement> agreements = approvalService.queryHTMLByAppId(approvalId);
		for (Agreement agreement2 : agreements) {
			if(agreement.getHtml() != null) {
				agreement.setHtml(agreement.getHtml()+agreement2.getHtml());
			}else {
				agreement.setHtml(agreement2.getHtml());
			}
		}
		JSONObject object = JSONObject.fromObject(agreement);
		ResponseUtil.write(response, object);
	}
	
	/**
	 * 根据ID查询批注信息
	 * @param approvalId
	 * @return
	 */
	@RequestMapping(value="/findAnnotationInfoByID")
	public ModelAndView findAnnotationInfoByID(String approvalId){
		ModelAndView mv =new ModelAndView();
		List<AnnotationInfo> annotationInfoList = new ArrayList<>();
		ApprovalEntity approvalEntity = approvalService.findApprovalEntityByID(Long.parseLong(approvalId));
		if(StringUtil.isNotEmpty(approvalEntity.getStatus02())){
			String[] approvalLevel = approvalEntity.getStatus02().split(",");
			
			if("1".equals(approvalEntity.getTypes())) {
				if(StringUtil.isNotEmpty(approvalEntity.getRemark05())){
					String[] ids = approvalEntity.getRemark05().split(",");
					AnnotationInfo annotationInfo1 = new AnnotationInfo();
					annotationInfo1.setAnnotationDate(approvalEntity.getRemark01());
					annotationInfo1.setDescription(approvalEntity.getApprover01());
					AnnotationInfo annotationInfo2 = new AnnotationInfo();
					annotationInfo2.setAnnotationDate(approvalEntity.getRemark02());
					annotationInfo2.setDescription(approvalEntity.getApprover02());
					AnnotationInfo annotationInfo3 = new AnnotationInfo();
					annotationInfo3.setAnnotationDate(approvalEntity.getRemark03());
					annotationInfo3.setDescription(approvalEntity.getApprover03());
					AnnotationInfo annotationInfo4 = new AnnotationInfo();
					annotationInfo4.setAnnotationDate(approvalEntity.getRemark04());
					annotationInfo4.setDescription(approvalEntity.getApprover04());
					if (ids.length == 1) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname());
						annotationInfoList.add(annotationInfo1);
					}
					if (ids.length == 2) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname());
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname());
						annotationInfoList.add(annotationInfo2);
					}
					if (ids.length == 3) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname());
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname());
						annotationInfoList.add(annotationInfo2);
						Staff staff3 = staffService.queryById(Long.parseLong(ids[2]));
						annotationInfo3.setAnnotationName(staff3.getSname());
						annotationInfoList.add(annotationInfo3);
					}
					if (ids.length == 4) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname());
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname());
						annotationInfoList.add(annotationInfo2);
						Staff staff3 = staffService.queryById(Long.parseLong(ids[2]));
						annotationInfo3.setAnnotationName(staff3.getSname());
						annotationInfoList.add(annotationInfo3);
						Staff staff4 = staffService.queryById(Long.parseLong(ids[3]));
						annotationInfo4.setAnnotationName(staff4.getSname());
						annotationInfoList.add(annotationInfo4);
					}
				}
			}else {
				
				if(StringUtil.isNotEmpty(approvalEntity.getRemark05())){
					String[] ids = approvalEntity.getRemark05().split(",");
					AnnotationInfo annotationInfo1 = new AnnotationInfo();
					annotationInfo1.setAnnotationDate(approvalEntity.getRemark01());
					annotationInfo1.setDescription(approvalEntity.getApprover01());
					AnnotationInfo annotationInfo2 = new AnnotationInfo();
					annotationInfo2.setAnnotationDate(approvalEntity.getRemark02());
					annotationInfo2.setDescription(approvalEntity.getApprover02());
					AnnotationInfo annotationInfo3 = new AnnotationInfo();
					annotationInfo3.setAnnotationDate(approvalEntity.getRemark03());
					annotationInfo3.setDescription(approvalEntity.getApprover03());
					AnnotationInfo annotationInfo4 = new AnnotationInfo();
					annotationInfo4.setAnnotationDate(approvalEntity.getRemark04());
					annotationInfo4.setDescription(approvalEntity.getApprover04());
					if (ids.length == 1) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname()+"["+approvalLevel[0]+"]");
						annotationInfoList.add(annotationInfo1);
					}
					if (ids.length == 2) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname()+"["+approvalLevel[0]+"]");
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname()+"["+approvalLevel[1]+"]");
						annotationInfoList.add(annotationInfo2);
					}
					if (ids.length == 3) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname()+"["+approvalLevel[0]+"]");
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname()+"["+approvalLevel[1]+"]");
						annotationInfoList.add(annotationInfo2);
						Staff staff3 = staffService.queryById(Long.parseLong(ids[2]));
						annotationInfo3.setAnnotationName(staff3.getSname()+"["+approvalLevel[2]+"]");
						annotationInfoList.add(annotationInfo3);
					}
					if (ids.length == 4) {
						Staff staff1 = staffService.queryById(Long.parseLong(ids[0]));
						annotationInfo1.setAnnotationName(staff1.getSname()+"["+approvalLevel[0]+"]");
						annotationInfoList.add(annotationInfo1);
						Staff staff2 = staffService.queryById(Long.parseLong(ids[1]));
						annotationInfo2.setAnnotationName(staff2.getSname()+"["+approvalLevel[1]+"]");
						annotationInfoList.add(annotationInfo2);
						Staff staff3 = staffService.queryById(Long.parseLong(ids[2]));
						annotationInfo3.setAnnotationName(staff3.getSname()+"["+approvalLevel[2]+"]");
						annotationInfoList.add(annotationInfo3);
						Staff staff4 = staffService.queryById(Long.parseLong(ids[3]));
						annotationInfo4.setAnnotationName(staff4.getSname()+"["+approvalLevel[3]+"]");
						annotationInfoList.add(annotationInfo4);
					}
				}
				
			}
			
		}
		
		mv.addObject("annotationInfoList", annotationInfoList);
		mv.setViewName("/approval/annotationInfo");
		return mv;
	}
	
	/**
	 * 表单打印
	 * @param approvalId
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/formPrint")
	public void formPrint(String approvalId, HttpServletResponse response) throws Exception {
		//根据approvalId 查询表单及内容
		ApprovalDetail approvalDetail = approvalService.selectForm(approvalId);
		
		List<ApprovalDetail> list = new ArrayList<>();
		if(approvalDetail.getmFields() != null && "" != approvalDetail.getmFields() ) {
			String[] split = approvalDetail.getmFields().split(",");
			String[] split2 = approvalDetail.getmValues().split(",");
			for(int i = 0; i < split.length; i ++) {
				ApprovalDetail approvalDetail2 = new ApprovalDetail();
				approvalDetail2.setRemark1(split[i]);
				approvalDetail2.setRemark2(split2[i]);
				
				list.add(approvalDetail2);
				approvalDetail2 = null;
			}
		}
		
		JsonConfig config = new JsonConfig();
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(list , config);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 查询审批信息
	 * @param approvalId
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/getSign")
	public void getSign(Long approvalId, HttpServletResponse response) throws Exception {
		ApprovalEntity approvalEntity = approvalService.findById(approvalId);
		
		//审批建议
		List<String> list = new ArrayList<>();
		if(approvalEntity.getApprover01() != null && approvalEntity.getApprover01() != "") {
			String approver01 = approvalEntity.getApprover01();
			list.add(approver01);
		}
		if(approvalEntity.getApprover02() != null && approvalEntity.getApprover02() != "") {
			String approver02 = approvalEntity.getApprover02();
			list.add(approver02);
		}
		if(approvalEntity.getApprover03() != null && approvalEntity.getApprover03() != "") {
			String approver03 = approvalEntity.getApprover03();
			list.add(approver03);
		}
		if(approvalEntity.getApprover04() != null && approvalEntity.getApprover04() != "") {
			String approver04 = approvalEntity.getApprover04();
			list.add(approver04);
		}
		
		//审批时间
		List<String> list2 = new ArrayList<>();
		if(approvalEntity.getRemark01() != null && approvalEntity.getRemark01() != "") {
			String remark01 = approvalEntity.getRemark01();
			list2.add(remark01);
		}
		if(approvalEntity.getRemark02() != null && approvalEntity.getRemark02() != "") {
			String remark02 = approvalEntity.getRemark02();
			list2.add(remark02);
		}
		if(approvalEntity.getRemark03() != null && approvalEntity.getRemark03() != "") {
			String remark03 = approvalEntity.getRemark03();
			list2.add(remark03);
		}
		if(approvalEntity.getRemark03() != null && approvalEntity.getRemark03() != "") {
			String remark04 = approvalEntity.getRemark03();
			list2.add(remark04);
		}
		
		List<ApprovalDetail> list3 = new ArrayList<>();
		
		
		if(approvalEntity.getRemark05() != null && approvalEntity.getRemark05() != "") {
			//审批人
			String[] split = approvalEntity.getRemark05().split(",");
			
			for(int i = 0; i < split.length; i ++) {
				ApprovalDetail approvalDetail2 = new ApprovalDetail();
				//审批人id
				approvalDetail2.setRemark1(split[i]);
				//审批建议
				approvalDetail2.setRemark2(list.get(i));
				//审批时间
				approvalDetail2.setRemark3(list2.get(i));
				
				//根据人员id查询人员姓名
				Staff staff = staffService.queryById(Long.valueOf(split[i]));
				approvalDetail2.setRemark4(staff.getSname());
				//图片路径
				approvalDetail2.setRemark1(staff.getSreserve1());
				list3.add(approvalDetail2);
				approvalDetail2 = null;
			}
		}
		
		JsonConfig config = new JsonConfig();
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(list3 , config);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 通过Jacob将doc转为HTML
	 * @throws Exception 
	 */
	@RequestMapping("/docToHtml")
	public void docToHtml(String docPath,HttpServletRequest request,HttpServletResponse response) throws Exception {
		//word文件路径及名称
		//docPath = "E:/develop/EclipseLuna/git/approval/src/main/webapp/attachment/" + docPath;
		docPath = RootPath.getRootPath("NATIVE_PATH") + docPath;
		//html文件路径及名称
		String fileName = docPath.substring(0,docPath.lastIndexOf("."))+".html";
		//创建Word对象，启动WINWORD.exe进程
		ActiveXComponent app = new ActiveXComponent("Word.Application");
		//设置用后台隐藏方式打开
		app.setProperty("Visible", new Variant(false));
		//获取操作word的document调用
		Dispatch documents = app.getProperty("Documents").toDispatch();
		//调用打开命令，同时传入word路径
		Dispatch doc = Dispatch.call(documents, "Open", docPath).toDispatch();
		//调用另外为命令，同时传入html的路径
		Dispatch.invoke(doc, "SaveAs", Dispatch.Method, 
			new Object[] { fileName, new Variant(8) }, new int[1]);
		//关闭document对象
		Dispatch.call(doc, "Close", new Variant(0));
		//关闭WINWORD.exe进程
		Dispatch.call(app, "Quit");
		//清空对象
		doc = null;
		app = null;
		String fileName1;
		fileName1 = fileName.substring(fileName.lastIndexOf("/")+1);
		try {
			String content = "charset=utf-8";
			String templateContent = "";
			FileInputStream fileinputstream = new FileInputStream(fileName);// 读取模板文件
			// 下面四行：获得输入流的长度，然后建一个该长度的数组，然后把输入流中的数据以字节的形式读入到数组中，然后关闭流
			int lenght = fileinputstream.available();
			byte bytes[] = new byte[lenght];
			fileinputstream.read(bytes);
			fileinputstream.close();
			// 通过使用默认字符集解码指定的 byte 数组，构造一个新的 
			// 因为原来的html文件是gb2312格式，所以转为string时也要以GBK格式读取，不然依旧是乱码
			templateContent = new String(bytes, "GBK");
			templateContent = templateContent.replaceFirst("charset=gb2312", content);
			// 因为已经替换字符串了，所以使用UTF-8字符集将此 String 编码为 byte 序列，并将结果存储到一个新的 byte 数组中。
			byte tag_bytes[] = templateContent.getBytes("UTF-8");
			FileOutputStream fileoutputstream = new FileOutputStream(fileName);// 建立文件输出流
			fileoutputstream.write(tag_bytes);
			fileoutputstream.close();
			} catch (Exception e) {
				System.out.print(e.toString());
			}
		ResponseUtil.write(response, fileName1);
	}
	
	/**
	 * 根据did查询人员总数
	 * @param staff
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/findStaffCountByDid")
	public void findStaffCountByDid(Staff staff,HttpServletResponse response) throws Exception{
		List<Staff> staffList = staffService.queryAllByMution(staff);
		if (staffList.size() == 0) {
			ResponseUtil.write(response, 0);
		} else {
			ResponseUtil.write(response, 1);
		}
	}

	/**
     * 根据名称数组名称查询名称数组类型
     * @param response
     * @param fieldNameArr 名称数组名称
	 * @throws Exception 
     */
    @RequestMapping("/queryFieldTypeByFieldNameArr")
    public void queryFieldTypeByFieldNameArr(HttpServletResponse response, String fieldNameArr) throws Exception{
    	String fieldType = approvalService.queryFieldTypeByFieldNameArr(fieldNameArr);
    	if (StringUtil.isNotEmpty(fieldType)) {
    		ResponseUtil.write(response, fieldType);
		} else {
			ResponseUtil.write(response, null);
		}
    }
}
